import React, {useState} from "react";
import {useThemeColors} from "../hooks/hooks.tsx";
import ApiService from "../../utils/ApiService";
import {FlashList} from "@shopify/flash-list";
import {Button, Icon, ListItem, makeStyles} from "@rn-vui/themed";
import {DeviceEventEmitter, Pressable, StyleSheet, Text, View} from "react-native";
import {RootSiblingPortal} from "react-native-root-siblings";
import OverLayer from "../components/OverLayer.tsx";
import DialogRestore from "./components/DialogRestore.tsx";

const useStyles = makeStyles((theme) => ({
    orderRow: {
        flexDirection: 'row',
        columnGap: 20,
        paddingVertical: 15,
        paddingHorizontal: 10,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBlockColor: theme.colors.grey4
    },
    orderCol: {},
    text1: {
        color: theme.colors.white,
        fontSize: 20,
        fontWeight: 'bold'
    },
    text2: {
        color: theme.colors.grey5,
        fontSize: 16,
    },
    col0: {
        flexGrow: 1
    },
    col1: {
        width: 100
    },
    col2: {
        width: 300
    },
    col3: {
        width: 100
    },
    footer: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        paddingVertical: 10,
        paddingHorizontal: 15
    },
    prodTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: theme.colors.safetyOrange
    },
    prodOptionTitle: {
        fontSize: 16,
        color: theme.colors.white
    },
}));

const OrderList = ({navigation, route}: any) => {
    const colors = useThemeColors();
    const styles = useStyles();
    const [offset, setOffset] = useState<number>(0);
    const [total, setTotal] = useState<number>(0);
    const [dataList, setDataList] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [refreshinng, setRefreshinng] = useState<boolean>(false);
    const [loadingMore, setLoadingMore] = useState<boolean>(false);
    const [order, setOrder] = useState<any>({});
    const restoreRef = React.useRef<any>(null);

    const fetchList = () => {
        ApiService.get('/pilot/orders', {
            params: {
                offset,
                limit: 10,
                dish_status: route.params?.status,
                order_direction: 'desc'
            }
        }).then((response: any) => {
            const {total, items} = response.data;
            setTotal(total);
            setDataList([...items]);
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            setLoading(false);
            setRefreshinng(false);
            setLoadingMore(false);
        });
    }

    const chooseOrder = (o: any) => {
        restoreRef.current.open(()=>{
            ApiService.put(`/pilot/orders/${o.id}/restore`).then(() => {
                DeviceEventEmitter.emit('ordersDidChanged');
                fetchList();
            });
        });
    }

    React.useLayoutEffect(() => {
        navigation.setOptions({
            headerTitle: route.params?.title,
        });

        fetchList();
    }, [route, navigation]);

    return (
        <>
            <FlashList
                estimatedItemSize={100}
                data={dataList}
                renderItem={({item, index}) => (
                    <Pressable style={styles.orderRow} onPress={() => chooseOrder(item)}>
                        <View style={[styles.orderCol, styles.col0]}>
                            {
                                item.items.map((prod: any, index: number) => (
                                    <View key={'item-' + prod.id}>
                                        <Text style={styles.prodTitle}>{prod.quantity + '*' + prod.title}</Text>
                                        <Text style={styles.prodOptionTitle}>
                                            {
                                                Object.values(prod.variations).filter((variation: any) => {
                                                    const value = variation.value ? variation.value : variation;
                                                    return !(/none/i.test(value) || /original/i.test(value));
                                                }).map((option: any, idx) => (
                                                    option.value ? option.value : option
                                                )).join(', ')
                                            }
                                        </Text>
                                    </View>
                                ))
                            }
                        </View>
                        <View style={[styles.orderCol, styles.col1]}>
                            <Text style={styles.text1}>{item.short_code}</Text>
                            <Text style={styles.text2}>{item.buyer_name}</Text>
                        </View>
                        <View style={[styles.orderCol, styles.col2]}>
                            <Text style={styles.text1}>{item.shipping?.first_name}</Text>
                            {
                                item.shipping?.phone_number ? (
                                    <Text>
                                        <Text style={styles.text2}>{item.shipping?.national_number}</Text>
                                        <Text style={styles.text2}>{item.shipping?.phone_number}</Text>
                                    </Text>
                                ) : null
                            }
                            <Text style={styles.text2}>{item.shipping?.formatted_address}</Text>
                        </View>
                        <View style={[styles.orderCol, styles.col3]}>
                            <Text style={styles.text2}>{item.shipping_method_title}</Text>
                        </View>
                    </Pressable>
                )}
                keyExtractor={(item: any) => 'order-' + item.id}
                ListHeaderComponent={
                    <View style={styles.orderRow}>
                        <View style={[styles.orderCol, styles.col0]}>
                            <Text style={styles.text1}>Detail</Text>
                        </View>
                        <View style={[styles.orderCol, styles.col1]}>
                            <Text style={styles.text1}>OrderN</Text>
                        </View>
                        <View style={[styles.orderCol, styles.col2]}>
                            <Text style={styles.text1}>Shipping To</Text>
                        </View>
                        <View style={[styles.orderCol, styles.col3]}>
                            <Text style={styles.text1}>ShippingM</Text>
                        </View>
                    </View>
                }
            />
            <View style={styles.footer}>
                <Pressable onPress={() => navigation.goBack()}>
                    <Icon
                        type={'entypo'}
                        name={'arrow-bold-left'}
                        size={40}
                        color={colors.white}
                    />
                </Pressable>
            </View>
            <DialogRestore ref={restoreRef}/>
        </>
    );
};

export default OrderList;
